package com.yheriatovych.reductor.example.model;

import com.google.auto.value.AutoValue;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.yheriatovych.reductor.annotations.CombinedState;
import com.yheriatovych.reductor.example.Utils;
import org.pcollections.ConsPStack;

import java.util.List;

/**
 * AppState 状态
 *
 * @since 2021-05-06
 */
@CombinedState
@AutoValue
public abstract class AppState {
    /**
     * 获得notes
     *
     * @return notes
     */
    public abstract List<Note> notes();

    /**
     * 获取过滤枚举
     *
     * @return 枚举对象
     */
    public abstract NotesFilter filter();

    /**
     * 通过gson获取一个TypeAdapter
     *
     * @param gson
     * @return TypeAdapter
     */
    public static TypeAdapter<AppState> typeAdapter(Gson gson) {
        return new AutoValue_AppState.GsonTypeAdapter(gson);
    }

    /**
     * 获取过滤后的note集合
     *
     * @return note集合
     */
    public List<Note> getFilteredNotes() {
        List<Note> notes = this.notes();
        NotesFilter filter = this.filter();
        return Utils.filter(ConsPStack.from(notes), note -> {
                if (filter == NotesFilter.ALL) {
                    return true;
                }
                return filter == NotesFilter.CHECKED && note.isChecked()
                        || filter == NotesFilter.UNCHECKED && !note.isChecked();
            }
        );
    }
}
